
<script setup>
	
	import port from './lib/port';
	import store from './lib/store';
	import { onLoad } from "@dcloudio/uni-app";
	import useFunction from './hook/useFunction';
	import { reactive, ref, computed } from 'vue';
	import c_paperitem from './components/workitem.vue';

	
	/** 词汇相关共享数据 */
	const storeData = store();
	
	/** 工具函数 */
	const toolFunction = useFunction();

	/** 词汇列表 */
	const flowlist = ref([])
	
	/** 参数 */
	const reqdata = reactive({
		page: 1,
		courseId: 0,
		ismore: true,
		pageSize: 50,
		box: storeData.query.box,
		learnId: storeData.query.learnId,
		learnType: storeData.query.learnType
	});

	/** 上一次播放位置 */
	const lastIndex = ref(0);

	/** 播放结束 */
	const playEnd = () => {
		flowlist.value[lastIndex.value].play = false;
	};

	/** 监听自然结束 */
	uni.useAudio.onEnded(playEnd);

	/** 监听播放暂停 */
	uni.useAudio.onStop(playEnd);

	/** 播放词汇 */
	const playEvent = (item, index) => {
		playEnd();
		lastIndex.value = index;
		item.play = true;
		uni.useAudio.src(item.voiceFile?.url);
		
		if (!item.playWord) {
			/** 首次点击 */
			item.playWord = true;
			item.blockTranslation = false;
			
		} else {
			/** 二次点击 */
			item.playWord = false;
			item.blockTranslation = true;
		};
	};

	/** 获取词汇列表 */
	async function getlistEvent() {
		if(!reqdata.ismore) return false;
		const { list, perPage, total } = await port.getWordsList_api(reqdata);
		reqdata.page++;
		flowlist.value = [...flowlist.value, ...list];
		if (list.length < perPage) reqdata.ismore = false;
	};
	
	/** 获取课程详情 */
	const getCourseInfo = async () => {
		const { course } = await port.getCourseDetail_api({ id: storeData.query.learnId });
		reqdata.courseId = course?.id;
		
		/** 设置课程 id */
		storeData.setQuery('courseId', course?.id);
		await getlistEvent();
	};
	
	/** 获取数据 */
	getCourseInfo();

	/** 临时数组 */
	const tempArray = ref(new Set());
	
	/** 临时数组长度 */
	const tempArraySize = computed(() => tempArray.value.size);

	/**  是否存在*/
	function in_array(search, array, flag = false) {
		for (const item of array) {
			if (flag === true && item.id === search) return true;
			else if (item === search || JSON.stringify(item) === JSON.stringify(search)) return true;
		};
		
		return false;
	};

	/** 错误词汇列表 */
	const wrongWords = ref([]);
	
	/** 正确词汇列表 */
	const rightWords = ref([]);

	/** 加入选择的词汇 */
	function joinEvent(type, word, index) {
		if (type === 1) {
			if (in_array(word.id, rightWords.value, true)) {
				rightWords.value = rightWords.value.filter(item => item.id !== word.id);
				word.change = 0;
				
			} else {
				rightWords.value.push(word);
				word.change = type;
			};
			
			wrongWords.value = wrongWords.value.filter(item => item.id !== word.id);
			
		} else if (type === 2) {
			if (in_array(word.id, wrongWords.value, true)) {
				wrongWords.value = wrongWords.value.filter(item => item.id !== word.id);
				word.change = 0;
				
			} else {
				word.change = type;
				wrongWords.value.push(word);
			};
			
			rightWords.value = rightWords.value.filter(item => item.id !== word.id);
		};
	};

	/** 自动选择词汇 */
	function handleAutoSelect() {
		if (tempArray.value.size < 45) {
			let count = 0;
			for (const item of flowlist.value) {
				if (tempArray.value.size < 45 && count < 45 && !tempArray.value.has(item.id) && item.change !== 1) {
					joinEvent(2, item);
					count++;
				};
				
				if (count >= 45) break;
			};
			
		} else {
			let count = 0;
			for (const item of flowlist.value) {
				if(item.change === 2) {
					item.change = 0;
					count++;
				};
				
				if (count >= 45) break;
			};
			
			tempArray.value.clear();
		};
	};

	/** 去复习 */
	async function handleBegin() {
		const param = { words: [], type: 2 };
		const newWords = [];
		rightWords.value.forEach(item => {
			param.words.push({ id: item.id, right: 1, type: 2 });
		});
		
		wrongWords.value.forEach(item => {
			const newItem = { id: item.id, right: 0, type: 2 };
			const findIndex = param.words.findIndex(({ id }) => id === item.id);
			!~findIndex ? param.words.push(newItem) : param.words.splice(findIndex, 1, newItem);
		});
		
		if (param.words.length == 0) {
			toolFunction.toast('请选择单词~');
			return false;
		};
		
		
		if (wrongWords.value.length) {
			/** 设置选择的错误词汇列表 */
			storeData.setlist('selectWordlist', wrongWords.value);
			
			/** 设置选择的正确词汇列表 */
			storeData.setlist('correctlist', rightWords.value);
			uni.redirectTo({
				url: '/pages/course/word/mark'
			});
			
		} else {
			await port.postLearnSubmit_api({ ...param, ...obj });
			uni.redirectTo({
				url: '/pages/course/word/plan'
			});
		};
	};
	
	
</script>

<template>
	<view class="containerbox">
		<uv-navbar title="复习" auto-back placeholder bg-color="#4d6d8a" left-icon-color="#fff" title-style="color:#fff"/>
		
		<scroll-view scrollY class="containerbox px-30" @scrolltolower="getlistEvent">
			<c_paperitem
				isback
				:item="item" 
				:index="index" 
				:iteration="3"
				:key="item.id"
				v-for="item,index in flowlist"
				@play="playEvent(item, index)"
				@joinEvent="joinEvent($event,item,index)"
			/>
		</scroll-view>
		
		<view class="flex items-center justify-between bottombox">
			<view class="flex-1 text-26 flex items-center text-white min-w-0">
				<view class="mr-20">正确<text class="mx-5 text-32 correct-color">{{ rightWords.length }}</text>个</view>
				<view class="">错误<text class="mx-5 text-32 mistake-color">{{ wrongWords.length }}</text>个</view>
			</view>
			
			<view class="flex-1 flex items-center">
				<view class="btn bgc-warning" @click="handleAutoSelect">{{ tempArraySize === 45 ? '全部取消' : '自动选择' }}</view>
				<view class="btn bgc-primary" @click="handleBegin">确认提交</view>
			</view>
		</view>
		
		<audio />
	</view>
</template>


<style lang="scss" scoped>
	@import "./style/common.scss";
	.btn:last-child{margin-left: 20rpx}
</style>